package com.dmall.opening.up.restful.application;

import com.dmall.opening.up.core.JsonType;
import com.dmall.opening.up.records.util.Jsons;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class JsonHttpMessageConverter extends AbstractHttpMessageConverter<JsonType> {

    public JsonHttpMessageConverter() {
        super(new MediaType("application", "json", StandardCharsets.UTF_8));
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return JsonType.class.isAssignableFrom(clazz);
    }

    @Override
    protected JsonType readInternal(Class<? extends JsonType> clazz, HttpInputMessage httpInputMessage) throws HttpMessageNotReadableException {
        return null;
    }

    @Override
    protected void writeInternal(JsonType jsonType, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
        Map<String, Object> entity = new HashMap<>();
        entity.put("code", 0);
        entity.put("data", jsonType.toJson());
        StreamUtils.copy(Jsons.toJsonString(entity), StandardCharsets.UTF_8, httpOutputMessage.getBody());
    }
}
